/*******************************************************************************
 *    系统名称   ：GMAgent服务系统
 *    公司      ： 成都欢娱乐互动
 *    文件名    ： AMF3Decoder.java
 *              (C) Copyright joyct Corporation 2011
 *               All Rights Reserved.
 * *****************************************************************************
 *    注意： 本内容仅限于 成都欢娱乐互动公司内部使用，禁止转发
 ******************************************************************************/
package com.ricky.core.net.protocol;

import java.nio.ByteOrder;

import org.apache.log4j.Logger;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

import com.ricky.core.net.ByteBuffer;
import com.ricky.core.net.protocol.FlashPolicyMsg;
import com.ricky.core.net.msg.AMF3Context;
import com.ricky.core.net.msg.ByteContext;
import com.ricky.core.net.msg.Context;
import com.ricky.core.net.utils.Attributes;


/***
 * 解码AMF3Decoder.java</br>
 * 
 * @author pu
 * @Data 2011-11-1</br>
 * @version v0.1</br>
 * @Discription
 ***/
public class AMF3Decoder extends CumulativeProtocolDecoder {
	protected static Logger log = Logger.getLogger(AMF3Decoder.class);

	private static int max=1024*1024*10;
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.apache.mina.filter.codec.CumulativeProtocolDecoder#doDecode(org.apache
	 * .mina.core.session.IoSession, org.apache.mina.core.buffer.IoBuffer,
	 * org.apache.mina.filter.codec.ProtocolDecoderOutput)
	 */
	@Override
	protected boolean doDecode(IoSession session, IoBuffer in,
			ProtocolDecoderOutput out) throws Exception {
		in.order(ByteOrder.BIG_ENDIAN);	
		try{
			if (in.prefixedDataAvailable(4,max)) { //<policy-file-request/>
				int length = in.getInt();// 读取消息内容长度
				session.setAttribute(Attributes.CURRENT_BUFFER_LENGTH, length);
				byte[] bytes = new byte[length];
				in.get(bytes);//读取类容
				//开始解码
				Context<?> context = new AMF3Context();
				context.decode(bytes);
				out.write(context);
				return true;
			}
			return false;
		}
		catch(Exception e)
		{
			byte[] bytes = new byte[in.remaining()];
			in.get(bytes);//读取类容
			String co=new String(bytes);
			System.out.println(co);
			
			Context<ByteBuffer> context = new ByteContext(0);
			ByteBuffer buffer=new ByteBuffer();
			buffer.writeUTF(FlashPolicyMsg.allow_all);
			context.setContent(buffer);
			out.write(context);
		}
		return false;
	}

}
